package com.acme.serialization;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.Socket;

/**
 * @author Gregory Sobko
 */
public class SerializationClient {
    private static Logger logger = Logger.getLogger(SerializationClient.class);

    public static void main(String[] args) throws IOException, SerializationException {
        String host = "localhost";
        if (args.length  < 1) {
            logger.warn("host not specified, using localhost...");
        } else {
            logger.info("Using host " + args[0]);
            host = args[0];
        }


        for (ObjectSerializer<SensorData[]> objectSerializer : SerializationServer.getProtocolSerializers().values()) {
            for(Integer num: new int[]{1, 1, 1, 10, 10, 10, 100, 100, 100, 1000, 10000, 100000}){
                long startTime = 0;
                try(Socket socket = new Socket(host, SerializationServer.PORT);
                    DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    BufferedReader serverReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                    PrintWriter serverWriter = new PrintWriter(dataOutputStream, true)){
                    startTime = System.currentTimeMillis();
                    serverWriter.println(objectSerializer.getProtocolName());
                    serverWriter.flush();
                    logger.info(serverReader.readLine());

                    logger.info("Sending batch of length: " + num);
        //            dataOutputStream.writeInt(num);
        //            dataOutputStream.flush();
                    SensorData[] sensorDatas = new SensorData[num];
                    for (int i = 0; i < num; i++) {
                        sensorDatas[i] = SensorData.generate();
                    }
                    objectSerializer.serialize(sensorDatas, dataOutputStream);
                    dataOutputStream.flush();
                    logger.info("All objects sent!");
                    logger.info(serverReader.readLine());
                }

                logger.info("Time elapsed: " + (System.currentTimeMillis() - startTime) + "ms");
                System.gc();
            }
        }
    }
}
